 package com.itic.market.mobile.pay;

import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.framework.utils.DateHelper;
import com.itic.appbase.framework.utils.NumberStringHelper;
import com.itic.appbase.framework.utils.RandomOrderNumHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.alipay.config.AlipayConfig;
import com.itic.appbase.framework.utils.alipay.util.AlipaySubmit;
import com.itic.market.mobile.base.BaseMobileInterface;
import com.itic.market.system.user.persistence.model.MarketUser;
/**
 * 友惠家商城中心接口类
 * @author 许小宝
 * 2017年07月25日  14时11分
 */
@Controller
@RequestMapping(value="/mobile/pay")
public class MarketPayInterface
     extends BaseMobileInterface {
	
	/*@RequestMapping(value="/success")
    @ResponseBody
	public Map<String,Object> success( HttpServletRequest request,HttpServletResponse response ){
		//添加提现记录信息表数据
		Tixian tixian = new Tixian();
		tixian.setId(IdGen.uuid());
		tixian.setIsEffective(DBConst.TRUE);
		tixian.setCreateUser(CREATE_USER);
		tixian.setOrgCode(ORG_CODE);
		tixian.setCreateTime(new Date());
		tixian.setUpdateTime(new Date());
		
		tixian.setUserId(userId);
		tixian.setType("0");
		tixian.setMoney(money);
		tixian.setIsGive("0");
		
		userMoney = NumberStringHelper.subtractString(userMoney, money);
		user.setMoney(userMoney);
		
		result = marketUserService.tixianCreate( user, tixian );
		errorCode = SUCCESS_ERROR_CODE;
    	errorMsg = SUCCESS_ERROR_MSG;
	}*/
    
    
    /**
     * 用户提现到支付宝或微信成功的回调接口
     * @param request
     * @param response
     * @param token
     * @param products
     * @return
     */
    @RequestMapping(value="/tixian")
    @ResponseBody
    public Map<String,Object> tixianCreate( HttpServletRequest request,HttpServletResponse response, String userId, String account, String accountName, String money){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		//判断必要的参数
    		if( StringHelper.isNotBlank(userId) && StringHelper.isNotBlank(money) && NumberStringHelper.isGreater(money, "1") && StringHelper.isNotBlank(account) && StringHelper.isNotBlank(accountName) ){
            	//减少用户的账户金额
    			MarketUser user = marketUserService.get(userId);
    			//判断用户的金额是否大于提现金额 
    			String userMoney = "0";
				if( StringHelper.isNotBlank(user.getMoney()) ){
					userMoney = user.getMoney();
				}
				if( NumberStringHelper.isGreater(userMoney, money) ){
					
					// 服务器异步通知页面路径
			        String notify_url = "http://" + request.getServerName() + ":"
			                + request.getServerPort() + request.getContextPath()
			                + "/alipay/alipayNotify";
			        // 需http://格式的完整路径，不能加?id=123这类自定义参数

			        //付款账号
			        String email = account;
			        //必填

			        //付款账户名
			        String account_name = accountName;
			        //必填，个人支付宝账号是真实姓名---公司支付宝账号是公司名称

			        //批次号
			        String batch_no = RandomOrderNumHelper.getOrderNumber();
			        //必填，格式：当天日期[8位]+序列号[3至16位]，如：201008010000001

			        //付款总金额
			        String batch_fee = money;
			        //必填，即参数detail_data的值中所有金额的总和

			        //付款笔数
			        String batch_num = "1";
			        //必填，即参数detail_data的值中，“|”字符出现的数量加1，最大支持1000笔（即“|”字符出现的数量999个）

			        //付款详细数据
			        String detail_data = batch_no+"^"+email+"^"+account_name+"^"+batch_fee+"^友惠家云店提现";
			        //必填，格式：流水号1^收款方帐号1^真实姓名^付款金额1^备注说明1|流水号2^收款方帐号2^真实姓名^付款金额2^备注说明2....
			        try {
			            batch_no = new String(request.getParameter("WIDbatch_no").getBytes("ISO-8859-1"),"UTF-8");
			            batch_fee = new String(request.getParameter("WIDbatch_fee").getBytes("ISO-8859-1"),"UTF-8");
			            detail_data = new String(request.getParameter("WIDdetail_data").getBytes("ISO-8859-1"),"UTF-8");
			        } catch (UnsupportedEncodingException e) {
			            e.printStackTrace();
			        }

			        AlipayConfig alipayConfig = new AlipayConfig();

			        //////////////////////////////////////////////////////////////////////////////////

			        //把请求参数打包成数组
			        Map<String, String> sParaTemp = new HashMap<String, String>();
			        sParaTemp.put("service", "batch_trans_notify");
			        sParaTemp.put("partner", alipayConfig.partner);
			        sParaTemp.put("_input_charset", alipayConfig.input_charset);
			        sParaTemp.put("notify_url", notify_url);
			        sParaTemp.put("email", email);
			        sParaTemp.put("account_name", account_name);
			        //付款当天日期//必填，格式：年[4位]月[2位]日[2位]，如：20100801
			        sParaTemp.put("pay_date", DateHelper.getDate("yyyyMMdd"));
			        sParaTemp.put("batch_no", batch_no);
			        sParaTemp.put("batch_fee", batch_fee);
			        sParaTemp.put("batch_num", batch_num);
			        sParaTemp.put("detail_data", detail_data);

			        /**建立请求*/
			        String sHtmlText = AlipaySubmit.buildRequest(sParaTemp,"get","确认");
			        System.out.println(sHtmlText);
			        //out(sHtmlText);
					
				}else{
					result = FAIL;
					errorCode = LESS_MONEY_ERROR_CODE;
	            	errorMsg = LESS_MONEY_ERROR_MSG;
				}
    		}
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	log(e);
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    }
    
    
    /**
     * 用户提现到支付宝或微信成功的回调接口
     * @param request
     * @param response
     * @param token
     * @param products
     * @return
     */
    @RequestMapping(value="/test")
    @ResponseBody
    public void test( HttpServletRequest request,HttpServletResponse response, String account, String accountName, String money){
    	// 服务器异步通知页面路径
        String notify_url = "http://" + request.getServerName() + ":"
                + request.getServerPort() + request.getContextPath()
                + "/alipay/alipayNotify";
        // 需http://格式的完整路径，不能加?id=123这类自定义参数

        //付款账号
        String email = account;
        //必填

        //付款账户名
        String account_name = accountName;
        //必填，个人支付宝账号是真实姓名---公司支付宝账号是公司名称

        //批次号
        String batch_no = RandomOrderNumHelper.getOrderNumber();
        //必填，格式：当天日期[8位]+序列号[3至16位]，如：201008010000001

        //付款总金额
        String batch_fee = money;
        //必填，即参数detail_data的值中所有金额的总和

        //付款笔数
        String batch_num = "1";
        //必填，即参数detail_data的值中，“|”字符出现的数量加1，最大支持1000笔（即“|”字符出现的数量999个）

        //付款详细数据
        String detail_data = "";
        //必填，格式：流水号1^收款方帐号1^真实姓名^付款金额1^备注说明1|流水号2^收款方帐号2^真实姓名^付款金额2^备注说明2....
        try {
            batch_no = new String(batch_no.getBytes("ISO-8859-1"),"UTF-8");
            batch_fee = new String(batch_fee.getBytes("ISO-8859-1"),"UTF-8");
            detail_data = new String(detail_data.getBytes("ISO-8859-1"),"UTF-8");
            AlipayConfig alipayConfig = new AlipayConfig();

            //////////////////////////////////////////////////////////////////////////////////

            //把请求参数打包成数组
            Map<String, String> sParaTemp = new HashMap<String, String>();
            sParaTemp.put("service", "batch_trans_notify");
            sParaTemp.put("partner", alipayConfig.partner);
            sParaTemp.put("_input_charset", alipayConfig.input_charset);
            sParaTemp.put("notify_url", notify_url);
            sParaTemp.put("email", email);
            sParaTemp.put("account_name", account_name);
            //付款当天日期//必填，格式：年[4位]月[2位]日[2位]，如：20100801
            sParaTemp.put("pay_date", DateHelper.getDate("yyyyMMdd"));
            sParaTemp.put("batch_no", batch_no);
            sParaTemp.put("batch_fee", batch_fee);
            sParaTemp.put("batch_num", batch_num);
            sParaTemp.put("detail_data", detail_data);

            /**建立请求*/
            String sHtmlText = AlipaySubmit.buildRequest(sParaTemp,"get","确认");
            PrintWriter out = response.getWriter();
            out.println(sHtmlText);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    
}